package vendingmachine

import net.iasolution.vendingmachine.constance.*

class InformationController {
	def index() {
		redirect(action: "welcome")
	}
	
	def welcome() {
        session.user == null
		return /*(session.user !=null) ?	redirect(action:"main") : */[]
	}
	
	def list() {
		println "list = ${params}"
		[]
	}
	
	def main() {
		
		if(params.uid!=null && params.token!=null){
				def user = authroization(params.uid,params.token)
				if(user!=null){
					session.user = user
					render(view:"list",
						   model:[matchInstanceList: PaymentMatch.findAllByCardId(user.cardId),
								  matchInstanceTotal: PaymentMatch.findAllByCardId(user.cardId),
								  user: session.user])
				}else{
					redirect(controller: "userProcess", action : "register")
				}
		}else{
            if(session.user==null){
                //redirect(url:VendingConstance.FACEBOOK_APP_URL)
                redirect(action : "welcome")
			}else {
                render(view:"list",model:[matchInstanceList: PaymentMatch.findAllByCardId(session.user.cardId),
                                          matchInstanceTotal: PaymentMatch.findAllByCardId(session.user.cardId),
					                      user: session.user])	
			}
		}
	}
	
	def logout() {
		session.user = null
		redirect(url:VendingConstance.FACEBOOK_APP_URL)
	}

	/**
	 * @return null = cannot find the user even if he is login from facebook
	 * */
	ShiroUser authroization(def uid , def token){
		return ShiroUser.findByFacebookId(uid)
	}
	
	def showCoupon() {
		def couponInstance = Coupon.get(params.id)
		if (!couponInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'coupon.label', default: 'Coupon'), params.id])
			redirect(action: "list")
			return
		}
		[couponInstance: couponInstance,user: session.user,
					   serialNumber:new Random().nextInt(10000)]
	}
    
    def showCouponsJSON() {
        def tmp = []
        if(params.uid!=null){
            def user = ShiroUser.get(params.uid)
            tmp = PaymentMatch.findAllByCardId(user?.cardId)
        }
        def result = []
        tmp.each{
            result.add([ card:it?.cardId, coupon_item:it?.coupon.item , coupon_detail:it?.coupon.description ])
        }
        render(contentType:"application/json") { 
            result=result
        }
	}
    
    
     def authByFB() {
        println params
        def result
        if(params.fid!=null){
            result = ShiroUser.findByFacebookId(params.fid)
        }
        render(contentType:"application/json") { 
            if(result!=null){
                userid=result?.id
                username=result?.username
            }else {
                message="the user not found"
            }
        }
	}
}
